﻿using Com.JunCaiSoft.AddressManage.Model;
using Com.JunCaiSoft.AddressManage.Entity;
using Com.JunCaiSoft.AddressManage.IDao;
using Com.JunCaiSoft.Common.Controller;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.API.AdministrativeManage.Controllers
{
    /// <summary>
    /// 行政区划
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class AdministrativeController : BaseController<AdministrativeView, AdministrativeItem, Administrative,String>
    {
        public AdministrativeController(IAdministrativeDao administrativedao) : base(administrativedao)
        {

        }
        /// <summary>
        /// 按行政区划ID批量删除
        /// </summary>
        /// <param name="DeleteList"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<ActionResult> DeleteListAsync(IEnumerable<String> DeleteList)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();
                int result = DaoAsync.DeleteListAsync<Administrative>(x => DeleteList.Contains(x.Code)).Result;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 获取省份列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ProvinceList()
        {
            try
            {
                var sql = @"select * from Administrative a
                                where a.Code = cast(a.Code as int)/10000 * 10000 
                                order by a.Code";
                List<SqlParameter> arrary = new List<SqlParameter>();
                var list = await DaoAsync.QuerySQLAsync<Administrative>(sql, arrary.Select(x => ((ICloneable)x).Clone()).ToArray());
                return await Task.Run(() => Content(JsonConvert.SerializeObject(list)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 获取地级市列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> CityList(String ProvinceCode)
        {
            try
            {
                var sql = @"select * from Administrative a
                                where 
                                a.Code = cast(a.Code as int)/100 * 100 and 
                                a.Code like @ProvinceCode ";
                List<SqlParameter> arrary = new List<SqlParameter>();

                SqlParameter para1 = new SqlParameter("@ProvinceCode", SqlDbType.VarChar);
                para1.Value = ProvinceCode != null ? (int.Parse(ProvinceCode) / 10000).ToString() + "%" : "''";

                arrary.Add(para1);

                if (ProvinceCode != "310000" && ProvinceCode != "120000" && ProvinceCode != "500000" && ProvinceCode != "110000")
                {
                    sql += @"and a.Code not like @ProvinceCodeSelf ";

                    SqlParameter para2 = new SqlParameter("@ProvinceCodeSelf", SqlDbType.VarChar);
                    para2.Value = ProvinceCode != null ? (int.Parse(ProvinceCode) / 10000 * 10000).ToString() : "''";

                    arrary.Add(para2);
                }

                if(ProvinceCode == "420000")
                {
                    sql += @"union
                             select * from Administrative a
                                    where 
                                    a.Code like '42900%' and 
                                    a.Code like @ProvinceCode ";
                }

                sql += "Order by a.Code";

                 
                var list = await DaoAsync.QuerySQLAsync<Administrative>(sql, arrary.Select(x => ((ICloneable)x).Clone()).ToArray());
                return await Task.Run(() => Content(JsonConvert.SerializeObject(list)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 获取县级市列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ZoneList(String CityCode)
        {
            try
            {
                var sql = @"select * from Administrative a
                                where a.Code != cast(a.Code as int)/100 * 100 and 
                                      a.Code != cast(a.Code as int)/10000 * 10000 and 
                                      a.Code like @CityCode ";
                List<SqlParameter> arrary = new List<SqlParameter>();

                SqlParameter para1 = new SqlParameter("@CityCode", SqlDbType.VarChar);
                para1.Value = CityCode != null ? (int.Parse(CityCode) / 100).ToString() + "%" : "''";

                if(CityCode != "310000" && CityCode != "120000" && CityCode != "500000" && CityCode != "110000")
                {
                    sql += "and a.Code not like @CityCodeSelf ";

                    SqlParameter para2 = new SqlParameter("@CityCodeSelf", SqlDbType.VarChar);
                    para2.Value = CityCode != null ? (int.Parse(CityCode) / 100 * 100).ToString() : "''";

                    arrary.Add(para2);
                }
                else
                {
                    para1.Value = CityCode != null ? (int.Parse(CityCode) / 100 + 1).ToString() + "%" : "''";
                }

                sql += "Order by a.Code";

                arrary.Add(para1); 
                var list = await DaoAsync.QuerySQLAsync<Administrative>(sql, arrary.Select(x => ((ICloneable)x).Clone()).ToArray());
                return await Task.Run(() => Content(JsonConvert.SerializeObject(list)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 根据行政编码获取地区名称
        /// </summary>
        /// <param name="AdministrativeCode"></param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> QueryByCode(String AdministrativeCode)
        {
            try
            {
                var list = DaoAsync.GetAsync(x=>x.Code == AdministrativeCode).Result;
                return await Task.Run(() => Content(JsonConvert.SerializeObject(list)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
